﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CloudFranceTriple.Models;
using CloudFranceTriple.WebRole.Models;
using WebMatrix.WebData;

namespace CloudFranceTriple.WebRole.Areas.Forum.Controllers
{
    public class PollController : BaseController
    {
        private cloudfrAboq2RsDMEntities db = new cloudfrAboq2RsDMEntities();

        private readonly IWebSecurityWrapper _webSecurity;
        public PollController()
        {
            this._webSecurity = new WebSecurityWrapper();
        }

        public PollController(IWebSecurityWrapper webSecurity)
            : base(webSecurity)
        {
            this._webSecurity = webSecurity;
        }

        //
        // GET: /Forum/Poll/AnswerId

        [Authorize(Roles = "RoleMember,RoleFans,RoleBaffMember,RoleAdminForum")]
        public ActionResult Poll(int id)
        {
            var _userId = base.UserId;
            var _answer = db.PollAnswerSet.Find(id);
            var _poll = db.PollSet.Find(_answer.Poll_Id);
            var HasPolled = _poll.PollAnswerSet.Join(db.PollUserSet.Where(pu2 => pu2.UserId == _userId), answer => answer.Id, pu => pu.PollAnswer_Id, (anwser, pu) => anwser.Id).Count() > 0;
            var ShowResults = DateTime.Compare((_poll.CreationDatePoll.AddDays(_poll.DurationInDays)), DateTime.UtcNow) < 0;

            if (!HasPolled & !ShowResults & (!_poll.IsMemberOnlyPoll | (User.IsInRole("RoleMember") & _poll.IsMemberOnlyPoll)))
            {
                db.PollAnswerSet.Find(id).NumberVotePollAnswer++;
                db.PollUserSet.Add(new PollUserSet() { PollAnswer_Id = id, UserId = GetProfile().UserId });
                db.SaveChanges();
            }

            if (_poll.ForumTopic_Id == null)
                return RedirectToAction("Index", "Home", new { area = "" });
            else
                return RedirectToAction("Index", "Post", new { area = "Forum", id = _answer.PollSet.ForumTopic_Id });
        }

        //
        // GET: /Forum/UnPoll/PollSet.Id

        [Authorize(Roles = "RoleMember,RoleFans,RoleBaffMember,RoleAdminForum")]
        public ActionResult Unpoll(int id)
        {
            Boolean HasPolled, ShowResults, IsTopicAuthor, IsRecruitPoll;

            var _userId = base.UserId;
            var _poll = db.PollSet.Find(id);
            IsRecruitPoll = _poll.IsRecruitPoll;
            HasPolled = _poll.PollAnswerSet.Join(db.PollUserSet.Where(pu2 => pu2.UserId == _userId), answer => answer.Id, pu => pu.PollAnswer_Id, (anwser, pu) => anwser.Id).Count() > 0;
            ShowResults = DateTime.Compare((_poll.CreationDatePoll.AddDays(_poll.DurationInDays)), DateTime.UtcNow) < 0;
            if (_poll.ForumTopic_Id != null)
                IsTopicAuthor = (_webSecurity.CurrentUserName == db.ForumTopicSet.Find(_poll.ForumTopic_Id).AuthorForumTopic);
            else
                IsTopicAuthor = User.IsInRole("RoleAuthorPollOnPortail");

            if (HasPolled && !ShowResults & (!IsRecruitPoll | (!IsTopicAuthor & IsRecruitPoll)))
            {

                Int32 _answerId = 0;
                _answerId = db.PollSet.Find(id).PollAnswerSet.Join(db.PollUserSet.Where(pu2 => pu2.UserId == _userId), answer => answer.Id, pu => pu.PollAnswer_Id, (answer, pu) => answer.Id).SingleOrDefault();

                db.PollAnswerSet.Find(_answerId).NumberVotePollAnswer--;
                db.PollUserSet.Remove(db.PollUserSet.Where(pu => (pu.UserId == _userId)).Where(pu2 => pu2.PollAnswer_Id == _answerId).Single());
                db.SaveChanges();
            }
            if (_poll.ForumTopic_Id == null)
                return RedirectToAction("Index", "Home", new { area = "" });
            else
                return RedirectToAction("Index", "Post", new { area = "Forum", id = db.PollSet.Find(id).ForumTopic_Id });
        }

        //
        // GET: /Forum/Poll/

        [AllowAnonymous]
        [Authorize(Roles = "RoleMember,RoleFans,RoleBaffMember,RoleAdminForum")]
        public ActionResult Index()
        {
            var _forumTopicAllowed = base.ForumTopicAllowed;
            var _userId = _webSecurity.CurrentUserId;
            var result = new List<PollItem>();

            ViewBag.IsAuthor = User.IsInRole("RoleAuthorPollOnPortail");


            var pollset = db.PollSet.Where(p3 => (_forumTopicAllowed.Contains(p3.ForumTopic_Id ?? 0)) || (p3.ForumTopic_Id == null)).AsParallel().OrderByDescending(p2 => p2.CreationDatePoll).ToList();

            foreach (PollSet poll in pollset)
            {
                result.Add(new PollItem
                {
                    Id = poll.Id,
                    LabelPoll = poll.LabelPoll,
                    DescriptionPoll = poll.DescriptionPoll,
                    CreationDatePoll = poll.CreationDatePoll,
                    DurationInDays = poll.DurationInDays,
                    ForumTopic_Id = poll.ForumTopic_Id,
                    IsPublicPollResult = poll.IsPublicPollResult,
                    IsMemberOnlyPoll = poll.IsMemberOnlyPoll,
                    IsRecruitPoll = poll.IsRecruitPoll,
                    OrderPoll = poll.OrderPoll,
                    LabelForumTopic = poll.ForumTopic_Id == null ? String.Empty : db.ForumTopicSet.Find(poll.ForumTopic_Id).LabelForumTopic,
                    ShowResults = (DateTime.Compare((poll.CreationDatePoll.AddDays(poll.DurationInDays)), DateTime.UtcNow) < 0),
                    HasPolled = poll.PollAnswerSet.Join(db.PollUserSet.Where(pu2 => pu2.UserId == _userId), answer => answer.Id, pu => pu.PollAnswer_Id, (anwser, pu) => anwser.Id).Count() > 0
                });
            }

            return View(result);
        }

        // PollId
        // GET: /Forum/Poll/Results/5

        [AllowAnonymous]
        public ActionResult Results(int id = 0)
        {
            PollSet pollset = db.PollSet.Find(id);
            if (pollset == null)
            {
                return HttpNotFound();
            }
            ViewBag.Topic_Id = pollset.ForumTopic_Id;
            return View(pollset);
        }

        // TopicId
        // GET: /Forum/Poll/Create

        [Authorize(Roles = "RoleMember,RoleFans,RoleBaffMember,RoleAdminForum")]
        public ActionResult Create(int? id=null)
        {
            ViewBag.Topic_Id = id;
            if (id != null && id > 0)
                ViewBag.TopicLabel = db.ForumTopicSet.Find(id).LabelForumTopic;
            return View(new PollSet { IsPublicPollResult = true, DurationInDays = 7 });
        }

        //
        // POST: /Forum/Poll/Create

        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        [Authorize(Roles = "RoleMember,RoleFans,RoleBaffMember,RoleAdminForum")]
        public ActionResult Create(PollSet pollset)
        {
            if (ModelState.IsValid)
            {
                if (pollset.ForumTopic_Id == 0) pollset.ForumTopic_Id = null;
                db.PollSet.Add(pollset);
                db.SaveChanges();

                if (pollset.ForumTopic_Id == null)
                    return RedirectToAction("Index", "Home", new { area = "" });
                else
                    return RedirectToAction("Index", "Post", new { id = pollset.ForumTopic_Id, area = "Forum" });
            }

            ViewBag.ForumTopic_Id = new SelectList(db.ForumTopicSet, "Id", "LabelForumTopic", pollset.ForumTopic_Id);
            return View(pollset);
        }

        //
        // GET: /Forum/Poll/Edit/5

        [Authorize(Roles = "RoleMember,RoleFans,RoleBaffMember,RoleAdminForum")]
        public ActionResult Edit(int id = 0)
        {
            PollSet pollset = db.PollSet.Find(id);
            if (pollset == null)
            {
                return HttpNotFound();
            }
            ViewBag.Topic_Id = pollset.ForumTopic_Id;
            ViewBag.ForumTopic_Id = new SelectList(db.ForumTopicSet, "Id", "LabelForumTopic", pollset.ForumTopic_Id);
            return View(pollset);
        }

        //
        // POST: /Forum/Poll/Edit/5

        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "RoleMember,RoleFans,RoleBaffMember,RoleAdminForum")]
        [ValidateInput(false)]
        public ActionResult Edit(PollSet pollset)
        {
            if (ModelState.IsValid)
            {
                if (pollset.ForumTopic_Id == 0) pollset.ForumTopic_Id = null;
                db.Entry(pollset).State = EntityState.Modified;
                db.SaveChanges();
                if (pollset.ForumTopic_Id == null)
                    return RedirectToAction("Index", "Home", new { area = "" });
                else
                    return RedirectToAction("Index", "Post", new { id = pollset.ForumTopic_Id, area = "Forum" });
            }
            ViewBag.ForumTopic_Id = new SelectList(db.ForumTopicSet, "Id", "LabelForumTopic", pollset.ForumTopic_Id);
            return View(pollset);
        }

        //
        // GET: /Forum/Poll/Delete/5

        [Authorize(Roles = "RoleMember,RoleFans,RoleBaffMember,RoleAdminForum")]
        public ActionResult Delete(int id = 0)
        {
            PollSet pollset = db.PollSet.Find(id);
            if (pollset == null)
            {
                return HttpNotFound();
            }
            ViewBag.Topic_Id = pollset.ForumTopic_Id;
            return View(pollset);
        }

        //
        // POST: /Forum/Poll/Delete/5

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "RoleMember,RoleFans,RoleBaffMember,RoleAdminForum")]
        public ActionResult DeleteConfirmed(int id)
        {
            PollSet pollset = db.PollSet.Find(id);
            var IsPollFromPortail = pollset.ForumTopic_Id == null;
            db.PollSet.Remove(pollset);
            db.SaveChanges();
            if (IsPollFromPortail)
                return RedirectToAction("Index", "Home", new { area = "" });
            else
                return RedirectToAction("Index", "Post", new { id = pollset.ForumTopic_Id, area = "Forum" });
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}